<script setup lang="jsx">
  import {watch,inject,ref,reactive,computed,onMounted} from 'vue'
  import { Message, Modal } from '@arco-design/web-vue'
  import supplierFee from '@/api/finance/supplierFee'
  import batchButton from '@/views/components/batchFeeButton.vue'
  const record = inject('record')
  const invoicesType = inject('invoicesType')
  const dictList = inject('dictList') //全部字典
  const feeTypeList = inject('feeTypeList') //费用类型
  const supplierList = inject('supplierList') //供应商
  const getRecord = inject('getRecord',()=>{})
  const span = inject('span')
  const title = ref('应付：')
  const amount = ref(0)
  const estimation_amount = ref(0)
  const tableRef = ref()
  const size=ref()
  const visible = ref(false)
  const formRef=ref()
  const dataList = ref([]);
  const auditShipmentStatus = ref(record.value.info.expense_audit == 1)
  const waybillId = ref(0)
  if(invoicesType.value=="shipment"){
    size.value='mini'
  }
  watch(record, (newVal, oldVal) => {
  if (newVal.id != undefined) {
    auditShipmentStatus.value = newVal.expense_audit
    waybillId.value = newVal.id
    tableList()
  }
})

const audit = async (type,record) => {
    let res;
    if(type){
      res = await supplierFee.auditPass({ids: [record.id]})
    } else{
      res = await supplierFee.auditRefuse({ids: [record.id]})
    } 
    if(!res.success){
      Message.error(res.message)
      return;
    }
    res.success && Message.success(res.message || `操作成功！`)
    if(type == false){
      auditShipmentStatus.value = type
    }
    tableList()
}
const auditShipment = async (type) => {
    let res;
    if(type){
      res = await supplierFee.auditPass({ids: [record.value.id],types:[4],invoicesType:invoicesType.value})
    } else{
      res = await supplierFee.auditRefuse({ids: [record.value.id],types:[44],invoicesType:invoicesType.value})
    } 
    if(!res.success){
      Message.error(res.message)
      return;
    }
    res.success && Message.success(res.message || `操作成功！`)
    auditShipmentStatus.value = type
    tableList()
}
// const getDictData = (key, value) => {
//     let label = ''
//   if(key=='fee_type'){
//     feeTypeList.value.map(i => {
//       if (value == i.id) {
//         label = i.fee_name
//       }
//     })
//   }else if(key=='unit'){
//     dictList.value.ChargeType.map(i => {
//       if (value == i.key) {
//         label = i.title
//       }
//     })
//   }else if(key=='currency'){
//     dictList.value.currencyType.map(i => {
//       if (value == i.key) {
//         label = i.title
//       }
//     })
//   }else if(key=='user_id'){
//     supplierList.value.map(i => {
//       if (value == i.id) {
//         label = i.name
//       }
//     })
//   }
//   return label
// }
const columnsData = ref([
  {title: '总费用', dataIndex: 'amount',width: 60,align:'center'},
  {title: '币种', slotName: 'currency',width: 40,align:'center'},
  {title: '汇率', dataIndex: 'exchange_rate',width: 40,align:'center'},
  {title: '供应商', slotName: 'user_id',width: 60,align:'center'},
  {title: '费用类型', slotName: 'fee_type',width: 80,align:'center'},
  {title: '描述', dataIndex: 'memo',width: 60,align:'center'},
  {title: '备注', dataIndex: 'remark',width: 60,align:'center'},
  {title: '业务时间', dataIndex: 'business_at',width: 110,align:'center'},
  {title: '操作', slotName: 'fixed',fixed: 'right',width: 107,align:'center'},
]);
const getCurrentDate = ()=> {
    const now = new Date();

    const year = now.getFullYear();

    // 注意：JavaScript的月份是从0开始的，所以需要加1
    const month = String(now.getMonth() + 1).padStart(2, '0');

    // 注意：JavaScript的日期也是从1开始的，所以不需要额外处理
    const date = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');

    return `${year}-${month}-${date} ${hours}:${minutes}:${seconds}`;
}
const formData = reactive({
      id:'',
      business_at: getCurrentDate(),
      currency:'',
      exchange_rate:null,
      fee_type:'',
      invoices_id:record.value.id,
      invoices_type:invoicesType.value,
      memo:'',
      remark:'',
      unit:'',
      unit_amount:'',
      user_id:'',
})
//币种改变  汇率清空
const currencyChange= (e)=>{
  formData.exchange_rate=null
}
dataList.value=record.value.expense
const rules = {
      business_at: [{ required: true, message:'请选择业务时间',validateTrigger: 'blur'}, ],
      fee_type: [{ required: true, message:'请选择费用类型',validateTrigger: 'blur'}, ],
      currency: [{ required: true, message:'请选择币种',validateTrigger: 'blur'}, ],
      unit: [{ required: true, message:'请选择单位',validateTrigger: 'blur'}, ],     
      user_id: [{ required: true, message:'请选择供应商服务',validateTrigger: 'blur'}, ],     
      unit_amount: [{required: true,message:'请输入单位费用', validateTrigger: 'blur'}, ],
    }
    const handleClick = () => {
      formData.id='';     
      formData.currency='';
      formData.exchange_rate=null;
      formData.fee_type='';
      formData.memo='';
      formData.remark='';
      formData.unit='';
      formData.unit_amount=null;
      formData.user_id='';
      formData.business_at=getCurrentDate()
      visible.value = true;
    };
    //详情数据
    const editAction = async (data) => {
      const res = await supplierFee.read(data.id)
        visible.value = true;   
        formData.business_at = res.data.business_at
        formData.id=res.data.id
        formData.currency=res.data.currency;
        formData.exchange_rate=res.data.exchange_rate;
        formData.fee_type=res.data.fee_type+'';
        formData.memo=res.data.memo;
        formData.remark=res.data.remark;
        formData.amount=res.data.amount;
        formData.business_at=res.data.business_at
        formData.user_id=res.data.user_id+'';
        formData.local_currency=res.data.local_currency;
        formData.local_amount=res.data.local_amount;
        formData.unit=res.data.unit+'';
        formData.unit_amount=Number(res.data.unit_amount);
        formData.estimation=res.data.estimation == 1;
    }
  //删除数据
  const deleteAction = async record => {
    const response = await supplierFee.deletes({ids: [record.id]})
    response.success && Message.success(response.message || `删除成功！`)
    tableList()
  }
//列表请求数据
let listData={
      pageSize:100,
      page:1,
      invoices_id :record.value.id
    }
    //列表
    const tableList = () => {
      supplierFee.getList(listData).then(res => {
        dataList.value =  res.data.items
        amountAdd()
      })      
    }
    //金额计算
    const amountAdd = () => {
      let total = 0
      let estimation = 0
        for(let i=0;i<dataList.value.length;i++){
          if(dataList.value[i].estimation == 0){
            total += parseFloat(dataList.value[i].local_amount,2) 
          }else{
            estimation += parseFloat(dataList.value[i].local_amount,2) 
          }
        }
      amount.value = total 
      estimation_amount.value = estimation
    };
    onMounted(() => {
     amountAdd()
    })
   //新增 //编辑
   const handleBeforeOk =async (formEl) => {
      if (!formEl) return
      await formEl.validate((valid) => {
        if (!valid) {
          if(formData.id==''){
            supplierFee.save(formData).then(res => {
              Message.success(res.message || `新增成功！`)
              visible.value = false;
              tableList()
            })
          }else{
            supplierFee.update(formData).then(res => {
              Message.success(res.message || `编辑成功！`)
              visible.value = false;
              tableList()
            })
          }
          
        }
      })  
    };
    const CostSharing = async (item) =>{
  if(invoicesType.value == 'waybill'){
      let res = await supplierFee.costSharingWaybill({fee_id:item.id,order_id:record.value.id,type:1})
      if(!res.success){
        return
      }
      Message.success(res.message)
      crudRef.value.refresh()
  }else if(invoicesType.value == 'delivery'){
    let res = await supplierFee.costSharingDelivery({fee_id:item.id,order_id:record.value.id,type:1})
      if(!res.success){
        return
      }
      Message.success(res.message)
      crudRef.value.refresh()
  }else{

  }
}
  
</script>

<template>
  <a-grid-item :span="span" class="g-collapse">
    <a-collapse :default-active-key="['1']">
      <a-collapse-item :header="title+(amount.toFixed(2))+' 预估:'+(estimation_amount.toFixed(2))" key="1" class="g-collapse-no-p">
        <template #extra>
          <a-button-group>
            <a-button  v-if="auditShipmentStatus == false" type="primary" size="mini" @click.stop="handleClick()" v-auth="['finance:supplierFee:save']"><icon-plus />添加</a-button>
            <batch-button
            :auditShipmentStatus="auditShipmentStatus"
            :auth="['finance:supplierFee:save']"
            :api="supplierFee.saveBatch"
            title="应付"
          />
            <a-popconfirm v-if="auditShipmentStatus == false"
                      content="确定要审计吗?"
                      position="bottom"
                      @click.stop=""
                      @ok="auditShipment(true)"
                  >
            <a-button type="primary" size="mini" v-auth="['finance:supplierFee:pass']"><icon-check />审计</a-button>
            </a-popconfirm>
            <a-popconfirm v-else
                      content="确定要反审计吗?"
                      position="bottom"
                      @click.stop=""
                      @ok="auditShipment(false)"
                  >
            <a-button type="primary" size="mini" v-auth="['finance:supplierFee:refuse']"><icon-close />反审计</a-button>
            </a-popconfirm>
          </a-button-group>
        </template>
      <a-table ref="tableRef" :columns="columnsData" :data="dataList" :bordered="false"  :size="size" column-resizable :pagination="false">
        <!--<template #fee_type="{ record }">
           {{getDictData('fee_type',record.fee_type)}} {{record.unit_amount  }}/{{getDictData('unit',record.unit) }} 
          </template>
          <template #currency="{ record }">
          {{getDictData('currency',record.currency)}}
          </template>
          <template #user_id="{ record }">
          {{getDictData('user_id',record.user_id)}}
          </template> -->
          <template #fee_type="{ record }">
           {{record.fee_type.fee_name}} {{record.unit_amount  }}/{{record.init_type.label}} 
           <a-tag v-if="record.estimation == 1" size="small" color="blue">估</a-tag>
           <a-tag v-if="record.is_shares == 1" size="small" color="red">摊</a-tag>
          </template>
          <template #currency="{ record }">
            {{record.currency_type.label}}
          </template>
          <template #user_id="{ record }">
            <div v-if="record.supplier!=null"> {{record.supplier.name}}</div>
          </template>
          <template #fixed="{ record }">
          <a-link v-if="record.status == 0" @click="editAction(record)" title="修改"><icon-edit /></a-link>
          <a-popconfirm v-if="record.status == 0 && (invoicesType != 'shipment' || record.share_id <= 0)"
                      content="确定要删除该数据吗?"
                      position="bottom"
                      @ok="deleteAction(record)"
                  >
                  <a-link title="删除" v-auth="['finance:supplierFee:delete']"><icon-delete /></a-link>
            </a-popconfirm>
            <a-popconfirm  v-if="record.status == 0 && (record.share_id <= 0 || record.share_id == record.id) && record.estimation == 0 "
                      content="确定通过审核吗?"
                      position="bottom"
                      @ok="audit(true,record)"
                  >
                  <a-link title="审核" v-auth="['finance:supplierFee:pass']"><icon-check /></a-link>
            </a-popconfirm>
            <a-popconfirm  v-if="record.status == 1 && (invoicesType != 'shipment' || record.share_id <= 0)"
                      content="确定反审核吗?"
                      position="bottom"
                      @ok="audit(false,record)"
                  >
                  <a-link title="反审核" v-auth="['finance:supplierFee:refuse']"><icon-close /></a-link>
            </a-popconfirm>
            <a-popconfirm  v-if="record.status == 1 && record.share_id <= 0 && invoicesType != 'shipment'"
                      content="确定分摊吗?"
                      position="bottom"
                      @ok="CostSharing(record)"
                  >
                  <a-link title="分摊" v-auth="['finance:supplierFee:refuse']"><icon-select-all />摊</a-link>
            </a-popconfirm>
          </template>
      </a-table>

      <a-drawer v-model:visible="visible" v-if="visible" width="800px">
        <template #title>
          <div >{{  formData.id == "" ? '新增' : '编辑'}}</div>
          </template>
          <a-form ref="formRef" :rules="rules" :model="formData">
            <a-form-item field="business_at" label="业务时间" validate-trigger="change">
              <a-date-picker
                style="width: 100%;"
                placeholder="请选择业务时间"
                show-time
                v-model="formData.business_at"
                format="YYYY-MM-DD HH:mm:ss"
              />
            </a-form-item>
            <a-form-item field="fee_type" label="费用类型">
              <a-select v-model="formData.fee_type" :options="feeTypeList" :field-names="{ value: 'id', label: 'fee_name' }"
                      placeholder="请选择费用类型" allow-clear allow-search :virtual-list-props="{height:200}" />  
            </a-form-item>
            <a-form-item field="currency" label="币种">
              <a-select v-model="formData.currency" @change="currencyChange"  :options="dictList.currencyType" :field-names="{ value: 'key', label: 'title' }"
            placeholder="请选择币种" allow-clear allow-search :virtual-list-props="{height:200}" />                     
            </a-form-item> 
            <a-form-item field="unit" label="单位">
              <a-select v-model="formData.unit" :options="dictList.ChargeType" :field-names="{ value: 'key', label: 'title' }"
            placeholder="请选择单位" allow-clear allow-search :virtual-list-props="{height:200}"/>                     
            </a-form-item> 
            <a-form-item field="user_id" label="供应商">
              <a-select v-model="formData.user_id" :options="supplierList" :field-names="{ value: 'id', label: 'name' }"
            placeholder="请选择供应商" allow-clear allow-search :virtual-list-props="{height:200}" />                     
            </a-form-item>         
            <a-form-item label="汇率" v-if="formData.currency!='CNY'">
              <a-input v-model="formData.exchange_rate"  placeholder="请输入汇率" />
            </a-form-item>
            <a-form-item field="unit_amount" label="单位费用" validate-trigger="blur">
              <a-input-number v-model="formData.unit_amount"  placeholder="请输入单位费用" />
            </a-form-item>
            <a-form-item label="总费用" v-if="formData.id!=''">
              <a-input v-model="formData.amount" disabled="true" placeholder="请输入总费用" />
            </a-form-item>
            <a-form-item label="本币币种" v-if="formData.id!=''">
              <a-input v-model="formData.local_currency" disabled="true" placeholder="请输入总费用" />
            </a-form-item>
            <a-form-item label="本币费用" v-if="formData.id!=''">
              <a-input v-model="formData.local_amount" disabled="true" placeholder="请输入总费用" />
            </a-form-item>
            <a-form-item label="描述">
              <a-textarea v-model="formData.memo"  placeholder="请输入描述" />
            </a-form-item>
            <a-form-item label="备注">
              <a-textarea v-model="formData.remark"  placeholder="请输入备注" />
            </a-form-item>     
            <a-form-item>
              <a-checkbox v-model="formData.estimation"> 预估 </a-checkbox>
            </a-form-item> 
        </a-form>
        <template #footer>        
          <a-button @click="visible = false">关闭</a-button>
          <a-button type="primary" @click="handleBeforeOk(formRef)">
            保存
          </a-button>
        </template>
      </a-drawer>
      </a-collapse-item>
    </a-collapse></a-grid-item>
</template>

<style>
.income-list ._crud-header,.income-list .mb-2,.income-list .operation-tools,.income-list .mb-1,.income-list ._crud-footer{
  display:none;
}

</style>